package team.kirohuji.service.impl.message;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.Topic;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import team.kirohuji.service.message.ProducerService;

@Service("producerService")
public class ProducerServiceImpl implements ProducerService {

	@Resource
	private JmsTemplate jmsTopicTemplate;

	@Resource
	private JmsTemplate jmsQueueTemplate;

	private Topic topic;
    @Override
	public void sendTopicMessage(Destination destination, String msg) {
		System.out.println("主题" + destination.toString() + "发送了消息------------" + msg);
		jmsTopicTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}
		});
	}
    @Override
	public void sendTopicMessage(String destination, String msg) {
		System.out.println("主题" + destination.toString() + "发送了消息------------" + msg);
		jmsTopicTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}
		});
	}

	/**
	 * 向默认主题发送消息
	 */
    @Override
	public void sendDefaultTopicMessage(String msg) {
		String destination = jmsTopicTemplate.getDefaultDestination().toString();
		System.out.println("向主题" + destination + "发送了消息------------" + msg);
		jmsTopicTemplate.send(new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}
		});
	}

	@Override
	public Topic setTopicName(String topicName) {
		try {
			return jmsTopicTemplate.getConnectionFactory().createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)
					.createTopic(topicName);
		} catch (JMSException e) {
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public void sendQueueMessage(Destination destination, String msg) {
		System.out.println("向队列" + destination + "发送了消息------------" + msg);
		jmsQueueTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}
		});
		
	}
	@Override
	public void sendQueueMessage(String destination, String msg) {
		System.out.println("向队列" + destination + "发送了消息------------" + msg);
		jmsQueueTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}
		});
		
	}
}